<template>
  <div class="fba-print-wrap clearfix">
    <div class="print-setting fl">
      <ChoosePrintList :selectWidth="210" ref="choosePrintRef" style="margin-bottom: 10px" @getLodop="getLodop">
        <template #bridgelabel>
          <p class="label">选择端桥：</p>
        </template>
        <template #printerlabel>
          <p class="label">选择打印机：</p>
        </template>
      </ChoosePrintList>
      <div class="set-item flex-c">
        <p class="label">打印份数：</p>
        <a-input-number size="small" v-model="editForm.num" :min="1" />
        <span class="unit">份</span>
      </div>
      <div class="set-item flex">
        <p class="label">图片尺寸：</p>
        <ul class="img-size-list">
          <li v-for="size in imgSizeList" :key="size" @click="editForm.imgSize = size" :style="{ width: size + 'px', height: size + 'px' }" :class="{ active: editForm.imgSize == size }">{{ size }}</li>
        </ul>
      </div>
      <div class="set-item" style="margin-top: 30px">
        <p>
          <span style="font-weight: bold">可选字段：</span>
          <span style="color: #999">最多可选7项</span>
        </p>
        <a-checkbox-group v-model="editForm.fieldList">
          <p style="margin: 20px 0 5px">单据字段：</p>
          <a-checkbox style="width: 115px; margin-right: 5px" v-for="(key, val) in billFieldList" :key="val" :value="val">{{ key }}</a-checkbox>
        </a-checkbox-group>
        <a-checkbox-group v-model="editForm.propsFieldList">
          <p style="margin: 20px 0 5px">产品属性：</p>
          <a-checkbox style="width: 115px; margin-right: 5px" v-for="(val, key) in propFieldMap" :key="key" :value="val.code">{{ val.name }}</a-checkbox>
        </a-checkbox-group>
      </div>
      <div class="handle-btn-w">
        <a-space>
          <a-button class="gray-outline" size="medium" @click="closePage">取消打印</a-button>
          <a-button type="primary" size="medium" @click="toPrintPre" :loading="submitLoading">确认打印</a-button>
          <!-- <a-button type="primary" size="medium" @click="toPrint" :loading="submitLoading">确认打印</a-button> -->
        </a-space>
      </div>
    </div>
    <div class="fba-list-w fl">
      <div id="tab01" style="overflow: hidden; margin-top: 10px; background-color: white" v-for="(item, index) in printList" :key="item.id">
        <table cellspacing="0" cellpadding="0" width="100%">
          <thead class="table-thead">
            <tr>
              <th :colspan="3 + editForm.fieldList.length + editForm.propsFieldList.length" style="font-weight: normal; font-size: 12px">
                <div style="display: flex; height: 30px; line-height: 30px">
                  <div style="font-size: 18px">出库单</div>
                  <div style="margin-left: 20px">打印人：{{ userInfo.userName }}</div>
                  <div style="margin-left: 20px">打印时间：{{ $setTime(new Date(), 'YYYY-MM-DD HH:mm') }}</div>
                  <div style="margin-left: 20px">共计：{{ printList.length }}单</div>
                  <div style="margin-left: 20px">sku{{ getSkuType() }}种{{ getSkuNum() }}件，包装{{ getPackType() }}种{{ getPackNum() }}件</div>
                </div>
              </th>
            </tr>
            <tr>
              <th style="border: 1px solid black; font-weight: normal; color: black; width: 100px; background: #d7d7d7; line-height: 30px">图片</th>
              <th style="border: 1px solid black; font-weight: normal; color: black; width: 100px; background: #d7d7d7; line-height: 30px">MSKU/SKU</th>
              <th style="border: 1px solid black; font-weight: normal; color: black; width: 100px; background: #d7d7d7; line-height: 30px">数量</th>
              <th v-for="(fildItem, fildIndex) in editForm.fieldList" :key="fildIndex" style="border: 1px solid black; font-weight: normal; color: black; width: 100px; background: #d7d7d7; line-height: 30px">
                <div>
                  <span>{{ billFieldList[fildItem] }}</span>
                  <span class="cursor" @click="editForm.fieldList.splice(fildIndex, 1)" v-if="index == 0 && !isAddLoading" style="margin-left: 10px; font-size: 16px">×</span>
                </div>
              </th>
              <th v-for="(propsFildItem, propsFildIndex) in editForm.propsFieldList" :key="propsFildIndex" style="border: 1px solid black; font-weight: normal; color: black; width: 100px; background: #d7d7d7; line-height: 30px">
                <div>
                  <span> {{ propFieldMap[propsFildItem].name }}</span>
                  <span class="cursor" @click="editForm.propsFieldList.splice(propsFildIndex, 1)" v-if="index == 0 && !isAddLoading" style="margin-left: 10px; font-size: 16px">×</span>
                </div>
              </th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td :colspan="3 + editForm.fieldList.length + editForm.propsFieldList.length" style="border: 1px solid #606266">
                <div style="width: 100%; height: 70px; background: #f2f2f2; display: flex">
                  <div style="width: 20%">
                    <img style="margin: 10px 0 0 10px; width: 60%" src="http://www.t-x-m.com/barcode.asp?bc1=123456789012&bc2=10&bc3=3.5&bc4=1.2&bc5=1&bc6=1&bc7=Arial&bc8=15&bc9=1" alt="" />
                  </div>
                  <div style="width: 20%; padding-top: 15px">
                    <div style="font-size: 12px">
                      <span style="color: #aaaaaa">店铺：</span>
                      <span style="font-size: 12px">123</span>
                    </div>
                    <div style="font-size: 12px">
                      <span style="color: #aaaaaa">平台单号：</span>
                      <span style="font-size: 12px">123</span>
                    </div>
                  </div>
                  <div style="width: 20%; padding-top: 15px">
                    <div style="font-size: 12px">
                      <span style="color: #aaaaaa">收货国家：</span>
                      <span style="font-size: 12px">123</span>
                    </div>
                    <div style="font-size: 12px">
                      <span style="color: #aaaaaa">发货仓：</span>
                      <span style="font-size: 12px">123</span>
                    </div>
                  </div>
                  <div style="width: 20%; padding-top: 15px">
                    <div style="font-size: 12px">
                      <span style="color: #aaaaaa">承诺发货时间：</span>
                      <span style="font-size: 12px">123</span>
                    </div>
                    <div style="font-size: 12px">
                      <span style="color: #aaaaaa">提交仓库时间：</span>
                      <span style="font-size: 12px">123</span>
                    </div>
                  </div>
                  <div style="width: 20%; padding-top: 15px">
                    <span style="font-size: 12px; color: red">123</span>
                    <div style="font-size: 12px">
                      <span style="color: #aaaaaa">拣货员：</span>
                      <span style="font-size: 12px">123</span>
                    </div>
                  </div>
                </div>
              </td>
            </tr>
            <tr v-for="productItem in item.packageItemList" :key="productItem.id">
              <td style="border: 1px solid #606266; width: 100px" align="center">
                <img :height="editForm.imgSize" :width="editForm.imgSize" :src="productItem.productPic" alt="" />
              </td>
              <td style="border: 1px solid #606266; width: 100px" align="center">
                <div>{{ productItem.msku }}/{{ productItem.productSku }}</div>
              </td>
              <td style="border: 1px solid #606266; width: 100px" align="center">{{ productItem.qtyPackageShipped }}</td>
              <td v-for="item in editForm.fieldList" :key="item" style="border: 1px solid #606266; width: 100px" align="center">{{ productItem[item] }}</td>
              <td v-for="item in editForm.propsFieldList" :key="item" style="border: 1px solid #606266; width: 100px" align="center">{{ getItemPropVvalue(productItem, propFieldMap[item]) }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import brcode from '@/assets/brcode.png'
  import { useRouter, useRoute } from 'vue-router'
  import useVisitedRouteStore from '@/store/modules/visited-routes'
  import useUserStore from '@/store/modules/user'
  import dayjs from 'dayjs'
  import { getRelatedList, getProductSKUList } from '@/api/product'
  import { findFbaShipmentPageByStore } from '@/api/purchase'
  import { printOutboundbill } from '@/api/order'
  import ChoosePrintList from '@/components/Print/choosePrintList.vue'
  import { Message } from '@arco-design/web-vue'

  onMounted(() => {
    getOrderList()
    getPropsList()
  })

  const visitedRouteStore = useVisitedRouteStore()
  const route: any = useRoute()
  const router: any = useRouter()
  const userInfo: any = useUserStore()
  const printList = ref<Array<any>>([])
  const submitLoading = ref(false)
  const isAddLoading = ref(false)
  const editForm = ref<any>({
    template: 1,
    num: 1,
    imgSize: 60,
    fieldList: [],
    propsFieldList: [],
  })
  const imgSizeList = ['80', '60', '44', '32']

  const billFieldList = {
    locationCode: '货位',
    packingName: '包装名称',
    packingSku: '包装SKU',
    packingWarehouseCode: '包装出货仓',
    salerName: '销售员',
    saasd: '定制单号',
    remark: '备注',

    // specValue: 'SKU规格',
  }
  const propFieldMap = ref<any>({})
  const propsInfoMap = ref<any>({})
  const specValueMap = ref<any>({})
  const choosePrintRef = ref()

  let LODOP: any = {}

  const getOrderList = async () => {
    if (!route.query.ids) return Message.error('没有选择打印的数据')
    let ids: any = route.query.ids.split(',') || []
    const res: any = await printOutboundbill(ids)

    printList.value = res?.data || []
  }

  // 获取所有属性列表
  async function getPropsList() {
    const res: any = await getRelatedList({
      pageSize: 1000,
      pageNum: 1,
    })
    propFieldMap.value = {}
    let list = res?.data?.records || []
    list.forEach((el: any) => {
      propFieldMap.value[el.code] = el
    })
  }
  // 获取当前sku的属性值
  function getCurrentSku(sku: string, key: string) {
    let props = propsInfoMap.value[sku]?.[key] || {}
    if ([2, 7, 8].includes(props.type)) {
      return props.valueStrList.length ? props.valueStrList.join(',') : '--'
    } else if (props.type == 2) {
      return props.valueBoolean ? '是' : '否'
    } else if (props.type == 6) {
      return props.valueBigDecimal || '--'
    } else if (props.type == 5) {
      return props.valueNumber || '--'
    } else {
      return props.valueStr || '--'
    }
  }
  // 获取当前sku的规格值
  function getSpecValue(sku: string) {
    let specValueList = specValueMap.value[sku] || []
    specValueList = specValueList.map((el: any) => el.valueCn)
    return specValueList?.join('*') || '--'
  }
  // 获取所有自定义显示字段
  function getFilxedList() {
    let list: Array<any> = []
    editForm.value.fieldList?.forEach((key: string) => {
      list.push({ name: billFieldList[key], key: key, type: 1 })
    })
    editForm.value.propsFieldList?.forEach((key: string) => {
      list.push({ name: propFieldMap.value[key]?.name, key: key, type: 2 })
    })
    return [...list]
  }

  // 关闭界面
  function closePage() {
    visitedRouteStore.removeVisitedRoute(route)
    router.go(-1)
  }
  function getLodop(val: any) {
    LODOP = val
  }
  function addPrint() {
    isAddLoading.value = true
    // 纸张初始化
    LODOP.PRINT_INIT('打印FBA货件')
    // 横向打印
    LODOP.SET_PRINT_PAGESIZE(2)

    //  指定打印机设备
    let { type, bridgeIDandName, printerIndex } = choosePrintRef.value.getBridgeInfo()
    if (type === 1) {
      LODOP.SET_BRIDGE_INDEX(bridgeIDandName + ',' + printerIndex)
    } else {
      LODOP.SET_PRINTER_INDEX(printerIndex)
    }

    LODOP.SET_SHOW_MODE('LANDSCAPE_DEFROTATED', 1)
    let tableConList = document.querySelectorAll('#tab01')

    tableConList.forEach((item: any, index: number) => {
      if (index > 0) {
        LODOP.NewPageA()
      }

      // table
      LODOP.ADD_PRINT_TABLE('10mm', '1%', '97%', 390, item?.innerHTML)
      LODOP.SET_PRINT_STYLEA(0, 'Vorient', 3)
      LODOP.SET_PRINT_STYLEA(0, 'LinkedItem', index * 6 + 1)

      LODOP.SET_PRINT_STYLE('FontSize', 14)
      LODOP.SET_PRINT_STYLE('Bold', 1)

      // 分页合计
      LODOP.ADD_PRINT_HTM('195mm', '45%', 200, 100, "<p style='font-size:12px'><span tdata='pageNO'>第##页</span>/<span tdata='pageCount'>共##页</span></p>")
      LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1)

      LODOP.SET_PRINT_COPIES(editForm.value.num || 1)
    })
    isAddLoading.value = false
  }
  // 打印预览
  function toPrintPre() {
    addPrint()
    LODOP.PREVIEW()
  }

  const getSkuType = () => {
    let itemArr: any = []
    let skuTypeNum: any = []
    printList.value.forEach((e) => {
      itemArr = [...itemArr, e.packageItemList]
    })
    itemArr.forEach((e: any) => {
      let index = skuTypeNum.findIndex((el: any) => e.productSku == el.productSku)
      if (index == -1) {
        skuTypeNum.push(e)
      }
    })
    return skuTypeNum.length
  }
  const getSkuNum = () => {
    let itemArr: any = []
    printList.value.forEach((e) => {
      itemArr = [...itemArr, e.packageItemList]
    })
    return itemArr.length
  }
  const getPackType = () => {
    let itemArr: any = []
    let skuTypeNum: any = []
    printList.value.forEach((e) => {
      itemArr = [...itemArr, e.packageItemList]
    })
    itemArr.forEach((e: any) => {
      let index = skuTypeNum.findIndex((el: any) => e.packingSku == el.packingSku)
      if (index == -1) {
        skuTypeNum.push(e)
      }
    })
    return skuTypeNum.length
  }
  const getPackNum = () => {
    let itemArr: any = []
    printList.value.forEach((e) => {
      itemArr = [...itemArr, e.packageItemList]
    })
    return itemArr.length
  }

  const getItemPropVvalue = (item: any, proItem: any) => {
    let propsList = proItem.propValueList
    console.log(item, propsList)
  }
</script>
<style lang="less" scoped>
  .ml20 {
    margin-left: 20px;
  }

  .fba-print-wrap {
    // display: flex;
    height: calc(100vh - @menuHeight);
    .print-setting {
      background-color: #fff;
      margin-right: 5px;
      height: 100%;
      width: 400px;
      padding: 20px;
      // overflow:auto

      .title {
        font-size: 16px;
        margin-bottom: 20px;
        font-weight: bold;
      }
      :deep(.printer-w .label) {
        width: 100px;
        flex-shrink: 0;
        text-align: right;
        color: var(--color-text-1);
      }
      .set-item {
        margin-bottom: 15px;
        .label {
          width: 100px;
          text-align: right;
          flex-shrink: 0;
        }
        .unit {
          line-height: 30px;
          background-color: var(--color-fill-2);
          padding: 0 12px;
          margin-left: 10px;
        }
      }
      .img-size-list {
        flex: 1;
        display: flex;
        align-items: flex-end;
        justify-content: space-between;
        li {
          border: 1px solid #dadde2;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 12px;
          &.active {
            border-color: rgb(var(--primary-6));
            color: rgb(var(--primary-6));
          }
        }
      }
      .handle-btn-w {
        display: flex;
        justify-content: flex-end;
        margin-top: 40px;
      }
    }

    .fba-list-w {
      width: calc(100% - 450px);
      height: calc(100vh - @menuHeight);
      overflow: auto;
      padding: 10px;
      // height: calc(100vh - @menuHeight);

      overflow-y: auto;
      margin-left: 5px;
      .table-thead {
        width: 100%;
        height: 30px;
        text-align: center;
        line-height: 30px;
        font-size: 12px;
        font-weight: normal;
      }
    }

    #tab01 {
      padding: 10px;
    }
  }
</style>
